package com.bl.mappio.transmit;

import com.bl.common.utils.PropertiesUtil;
import com.bl.mappio.transmit.handler.TransmitAcceptHandler;
import com.bl.nio.common.entity.Transport;

import java.io.IOException;
import java.net.BindException;
import java.net.ServerSocket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author 作者 : blownsow
 * @version 版本: 1.0
 * @date 创建时间 : 2019/12/7 8:54
 * @describe 类描述:
 */
public class TransmitServer {
    private ExecutorService executorService = Executors.newCachedThreadPool();

    private ServerSocket serverSocket;

    private Transport transport;

    public TransmitServer(int port) throws BindException {
        int startPort = Integer.parseInt(PropertiesUtil.get("transmit.start.port").toString());
        int stopPort = Integer.parseInt(PropertiesUtil.get("transmit.stop.port").toString());
        String exclude = PropertiesUtil.get("transmit.exclude.port").toString();

        if ((port < startPort || port > stopPort) && !exclude.contains(port+"")){
            System.out.println(port + "超出服务器代理端口范围");
            throw new BindException("超出服务器代理端口范围");
        }else{
            transport = new Transport(port);
            try {
                serverSocket = transport.newServerSocket();
                executorService.execute(new TransmitAcceptHandler(serverSocket));
                System.out.println("开启转发服务器端口，"+port);
            } catch (BindException e) {
                System.out.println(port + "端口已被绑定");
                throw new BindException("端口已被绑定");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public void close(){
        try {
            serverSocket.close();
            executorService.shutdownNow();
            System.out.println("关闭转发服务器成功,"+transport.getPort());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
